<template>
  <div class="address-page">
    <h1 class="page-title">收货地址管理</h1>

    <!-- 添加地址按钮 -->
    <el-button type="primary" @click="openAddDialog" class="add-button">添加新地址</el-button>

    <!-- 地址列表 -->
    <div class="address-list">
      <div v-for="address in addresses" :key="address.addressId" class="address-card">
        <div class="address-info">
          <p><strong>收货人：</strong>{{ address.username }}</p>
          <p><strong>电话：</strong>{{ address.phone }}</p>
          <p><strong>地址：</strong>{{ address.addressDetail }}</p>
          <p><strong>默认地址：</strong>{{ address.isDefault === 1 ? '是' : '否' }}</p>
          <p><strong>创建时间：</strong>{{ address.createdAt }}</p>
          <p><strong>更新时间：</strong>{{ address.updatedAt }}</p>
        </div>
        <div class="address-actions">
          <el-button type="primary" @click="openEditDialog(address)" class="action-button">编辑</el-button>
          <el-button
              type="success"
              @click="setDefaultAddress(address.addressId)"
              :disabled="address.isDefault === 1"
              class="action-button"
          >
            设为默认
          </el-button>
          <el-button type="danger" @click="deleteAddress(address.addressId)" class="action-button">删除</el-button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑地址的对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑地址' : '添加新地址'"
        width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="收货人姓名">
          <el-input v-model="form.username" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="收货人电话">
          <el-input v-model="form.phone" placeholder="请输入收货人电话"/>
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input
              v-model="form.addressDetail"
              type="textarea"
              placeholder="请输入收货地址"
          />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="2"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {ElMessageBox} from 'element-plus';
import {apiGet, apiPost} from '@/utils/api';
import type {Address} from '@/types/entity';
import {useUserStore} from '@/store/modules/user';

const userStore = useUserStore();

// 定义响应式的地址列表
const addresses = ref<Address[]>([]);

// 对话框是否可见
const dialogVisible = ref(false);
// 是否是编辑模式
const isEdit = ref(false);
// 表单数据
const form = ref({
  addressId: 0,
  userId: userStore.id, // 假设从用户信息中获取
  username: '',
  phone: '',
  addressDetail: '',
  isDefault: 2, // 默认非默认地址
});

// 从后端获取地址列表
const fetchAddresses = async () => {
  const {data} = await apiGet('/address/getAllByUserId', {userId: form.value.userId});
  addresses.value = data;
};

// 打开添加地址对话框
const openAddDialog = () => {
  isEdit.value = false;
  form.value = {
    addressId: 0,
    userId: form.value.userId,
    username: '',
    phone: '',
    addressDetail: '',
    isDefault: 2,
  };
  dialogVisible.value = true;
};

// 打开编辑地址对话框
const openEditDialog = (address: Address) => {
  isEdit.value = true;
  form.value = {...address};
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (isEdit.value) {
    // 编辑地址
    await apiPost('/address/edit', form.value);
  } else {
    // 添加地址
    await apiPost('/address/add', form.value);
  }
  dialogVisible.value = false;
  await fetchAddresses(); // 刷新地址列表
};

// 设置默认地址
const setDefaultAddress = async (addressId: number) => {
  await apiPost('/address/edit', {addressId, userId: form.value.userId, isDefault: 1});
  await fetchAddresses(); // 刷新地址列表
};

// 删除地址
const deleteAddress = async (addressId: number) => {
  await ElMessageBox.confirm('确定删除该地址吗？', '提示', {
    type: 'warning',
  });
  await apiPost('/address/delete', {addressId});
  await fetchAddresses(); // 刷新地址列表
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchAddresses();
});
</script>

<style scoped>
.address-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
  text-align: center;
}

.add-button {
  margin-bottom: 20px;
  width: 100%;
  max-width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.address-list {
  margin-top: 20px;
}

.address-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  transition: box-shadow 0.3s ease;
}

.address-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.address-info {
  flex: 1;
}

.address-info p {
  margin: 8px 0;
  color: #606266;
}

.address-actions {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-button {
  width: 100px;
}

.el-button {
  margin-left: 10px;
}
</style>